// Ninf-G-XX, ver. 0.1
// Copyright 2011 National Institute of Advanced Industrial Science and Technology
// 
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
// 
//     http://www.apache.org/licenses/LICENSE-2.0
// 
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <string>
#include "FpOutputStream.hpp"
#include "Exception.hpp"

using namespace std;
using namespace ninf::lib;

FpOutputStream :: FpOutputStream(FILE * fp): fp(fp), closed(true){}

FpOutputStream :: FpOutputStream(const char * filename): closed(false){
		init(filename);
}

FpOutputStream :: FpOutputStream(const std::string & filename):closed(false){
		init(filename.c_str());
}


FpOutputStream :: ~FpOutputStream(){
  if (!closed)
    fclose(fp);
}


/* write out a single byte */
void
FpOutputStream :: write(int c){
  unsigned char c0 = (unsigned char)c;
  if (fwrite(&c0, 1, 1, fp) <= 0)
    EXCEPTION("fwrite");
}

/* write out array of bytes */
void
FpOutputStream :: write(const char * val, int offset, int len){
  if (fwrite(val + offset, 1, len, fp) <= 0)
    EXCEPTION("fwrite");
}

/* flush the underlying stream */
void 
FpOutputStream :: flush(){
  fflush(fp);
}


/* close the underlying stream */
void 
FpOutputStream :: close(){
  if (!closed)
    fclose(fp);
  closed = true;
}


void 
FpOutputStream :: init(const char * filename) {
  fp = fopen(filename, "w");
  if (fp == NULL){
    string tmp("cannot open file '");
    tmp += filename;
    tmp += "'";
    EXCEPTION(tmp);
  }
}
